package com.heartline.util;

import com.alibaba.fastjson.JSONObject;
import com.heartline.init.Env;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;

/**
 * 七牛云上传文件
 * <p>
 * 存储区域	地域简称	上传域名
 * 华东	z0	服务器端上传：http(s)://up.qiniup.com
 * 客户端上传： http(s)://upload.qiniup.com
 * 华北	z1	服务器端上传：http(s)://up-z1.qiniup.com
 * 客户端上传：http(s)://upload-z1.qiniup.com
 * 华南	z2	服务器端上传：http(s)://up-z2.qiniup.com
 * 客户端上传：http(s)://upload-z2.qiniup.com
 * Created by zhy on 2018/6/12.
 */
public class QiNiuUploader {

    public void uploadByBase64(String fileName, String base64, Integer fileSize) throws Exception {
        try {
            String token = getToken();
            if (fileSize == null) {
                fileSize = Base64.decode(base64, 0).length;
            }
            String url = "http://up-z2.qiniu.com/putb64/" + fileSize + "/key/" + UrlSafeBase64.encodeToString(fileName);

            Response response = Request.Post(url)
                    .addHeader("Content-Type", "application/octet-stream")
                    .addHeader("Authorization", "UpToken " + token)
                    .bodyByteArray(base64.getBytes())
                    .execute();

            System.out.println(response.returnResponse().getStatusLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //上传图片token
    private String getToken() throws Exception {
        //设置好账号的ACCESS_KEY和SECRET_KEY
        SecretKeySpec secretKeySpec = new SecretKeySpec(Env.get("qiniu.secret_key", "secret_key").getBytes(), "HmacSHA1");
        long deadline = System.currentTimeMillis() / 1000L + 3600;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scope", Env.get("qiniu.bucketname", "bucketname"));
        jsonObject.put("deadline", deadline);

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKeySpec);
        String s = UrlSafeBase64.encodeToString(jsonObject.toJSONString());
        String encodedSign = UrlSafeBase64.encodeToString(mac.doFinal(s.getBytes()));
        String token = Env.get("qiniu.access_key", "access_key") + ":" + encodedSign + ":" + s;
        System.out.println(token);
        return token;
    }
}
